package com.kkd.kkdapp.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.kkd.kkdapp.view.CustomProgressDialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AppUtil {

	public static int ITEM_IMG_WIDTH;
	public static int ITEM_IMG_HEIGHT;
	public static int GALLERY_WIDTH;
	public static int GALLERY_HEIGHT;
	public static int currentFontSizeFlag = 1; // 字体大小标志位，0代表normal，1代表larger，2代表largest
	private static Handler mHandler = new Handler();

	/**
	 * 改变字体的大小
	 * 
	 * @param webView
	 */
	public static void changeFont(WebView webView) {
		int toSetFlag = (++currentFontSizeFlag) % 3;
		switch (toSetFlag) {
		case 0:
			webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
			break;
		case 1:
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGER);
			break;
		case 2:
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
			break;
		default:
			break;
		}
		currentFontSizeFlag = toSetFlag;
	}

	/**
	 * 设置一个WebView的字体的大小
	 * 
	 * @param webView
	 */
	public static void setFont(WebView webView) {
		switch (currentFontSizeFlag) {
		case 0:
			webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
			break;
		case 1:
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGER);
			break;
		case 2:
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
			break;
		default:
			break;
		}
	}

	/**
	 * 返回当前字号的字符串表示
	 * 
	 * @return
	 */
	public static String getCurrentFontString() {
		switch (currentFontSizeFlag) {
		case 0:
			return "小";
		case 1:
			return "中";
		case 2:
			return "大";
		default:
			return "未知";
		}
	}

	/**
	 * 设置WebView的布局显示，如果详细内容包含table标签，则不设置webview为单列
	 * 
	 * @param webView
	 * @param content
	 * @return
	 */
	public static void setWebViewLayout(WebView webView, String content) {
		if (content.contains("<table")) {
			webView.getSettings().setLayoutAlgorithm(
					LayoutAlgorithm.NARROW_COLUMNS);
		} else {
			webView.getSettings().setLayoutAlgorithm(
					LayoutAlgorithm.SINGLE_COLUMN);
		}
	}

	final static String[] hex = { "%00", "%01", "%02", "%03", "%04", "%05",
			"%06", "%07", "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e",
			"%0f", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
			"%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f", "%20",
			"%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29",
			"%2a", "%2b", "%2c", "%2d", "%2e", "%2f", "%30", "%31", "%32",
			"%33", "%34", "%35", "%36", "%37", "%38", "%39", "%3a", "%3b",
			"%3c", "%3d", "%3e", "%3f", "%40", "%41", "%42", "%43", "%44",
			"%45", "%46", "%47", "%48", "%49", "%4a", "%4b", "%4c", "%4d",
			"%4e", "%4f", "%50", "%51", "%52", "%53", "%54", "%55", "%56",
			"%57", "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
			"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68",
			"%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f", "%70", "%71",
			"%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7a",
			"%7b", "%7c", "%7d", "%7e", "%7f", "%80", "%81", "%82", "%83",
			"%84", "%85", "%86", "%87", "%88", "%89", "%8a", "%8b", "%8c",
			"%8d", "%8e", "%8f", "%90", "%91", "%92", "%93", "%94", "%95",
			"%96", "%97", "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e",
			"%9f", "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
			"%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af", "%b0",
			"%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7", "%b8", "%b9",
			"%ba", "%bb", "%bc", "%bd", "%be", "%bf", "%c0", "%c1", "%c2",
			"%c3", "%c4", "%c5", "%c6", "%c7", "%c8", "%c9", "%ca", "%cb",
			"%cc", "%cd", "%ce", "%cf", "%d0", "%d1", "%d2", "%d3", "%d4",
			"%d5", "%d6", "%d7", "%d8", "%d9", "%da", "%db", "%dc", "%dd",
			"%de", "%df", "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6",
			"%e7", "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
			"%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7", "%f8",
			"%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff" };

	/**
	 * 将特殊字符转换为HEX编码
	 * 
	 * @param s
	 * @return
	 */
	public static String encode(String s) {
		StringBuffer sbuf = new StringBuffer();
		int len = s.length();
		for (int i = 0; i < len; i++) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') { // '0'..'9'
				sbuf.append((char) ch);
			} else if (ch == ' ') { // space
				sbuf.append('+');
			} else if (ch == '-'
					|| ch == '_' // unreserved
					|| ch == '.' || ch == '!' || ch == '~' || ch == '*'
					|| ch == '\'' || ch == '(' || ch == ')') {
				sbuf.append((char) ch);
			} else if (ch <= 0x007f) { // other ASCII
				sbuf.append(hex[ch]);
			} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
				sbuf.append(hex[0xc0 | (ch >> 6)]);
				sbuf.append(hex[0x80 | (ch & 0x3F)]);
			} else { // 0x7FF < ch <= 0xFFFF
				sbuf.append(hex[0xe0 | (ch >> 12)]);
				sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
				sbuf.append(hex[0x80 | (ch & 0x3F)]);
			}
		}
		return sbuf.toString();
	}

	/**
	 * 补全XML
	 * 
	 * @param oldStream
	 * @return
	 */
	public static InputStream transferInputStream(InputStream oldStream) {
		InputStream newStream = null;
		String tmpString = null;

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[4096];
		int count = -1;
		try {
			while ((count = oldStream.read(data, 0, 4096)) != -1)
				outStream.write(data, 0, count);
		} catch (IOException e) {
			e.printStackTrace();
		}

		data = null;
		try {
			tmpString = new String(outStream.toByteArray(), "GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		;

		tmpString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><DATA>"
				+ tmpString;
		tmpString += "</DATA>";
		Log.i("xmlstring", tmpString);
		try {
			newStream = new ByteArrayInputStream(tmpString.getBytes("UTF-8"));
			Log.e("afterString", newStream.toString());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return newStream;
	}

	/**
	 * 
	 * @Title:isConnect
	 * @Description:TODO(判断网络是否连接)
	 * @param:@param context
	 * @param:@return
	 * @return:boolean
	 */
	public static boolean isConnect(Context context) {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		boolean ret = false;
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						ret = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
			ret = false;
		}
		return ret;
	}

	public static boolean checkNet(Context context) {
		// 判断网络是否连接
		if (isConnect(context) == false) {
			new AlertDialog.Builder(context)
					.setTitle("网络错误")
					.setMessage("网络连接失败，请确认网络连接")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
									// TODO Auto-generated method stub
									android.os.Process
											.killProcess(android.os.Process
													.myPid());
									System.exit(0);
								}
							}).show();
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 得到自定义的progressDialog
	 * 
	 * @param context
	 * @param msg
	 * @return
	 */
	public static CustomProgressDialog progressDialog;

	public static void startProgressDialog(Context mContext, String msg) {

		progressDialog = CustomProgressDialog.show(mContext, msg);
		progressDialog.setCanceledOnTouchOutside(false);

	}

	/**
	 * 关闭自定义的progressDialog
	 * 
	 * @param context
	 * @param msg
	 * @return
	 */

	public static void stopProgressDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.closeDialog();
		}
	}

	/**
	 * 自定义样式的Toast
	 */

	public static Dialog mDialog;
	public static Timer mTimer;
	public static View viewCustomer;
	public static RelativeLayout rel_toast;
	public static TextView tv_content;
	public static onToastDismiss mDismissListener;

	public static void makeToastForCustomer(Context mContext, String content) {
		if (viewCustomer != null) {
			viewCustomer = null;
		}
		if (tv_content != null) {
			tv_content = null;
		}
		if (rel_toast != null) {
			rel_toast = null;
		}

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		mDismissListener = null;
		try {
			viewCustomer = LayoutInflater.from(mContext).inflate(
					R.layout.toast_item_dialog, null);
			tv_content = (TextView) viewCustomer.findViewById(R.id.tv_content);
			rel_toast = (RelativeLayout) viewCustomer
					.findViewById(R.id.rel_toast);
			rel_toast.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {
					closeDialog();
				}
			});
			tv_content.setText(content);
			mDialog = new Dialog(mContext, R.style.TransparentDialog_Toast);
			mDialog.setContentView(viewCustomer);
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setCancelable(false);
			mDialog.show();
			AlphaAnimation alphaIn = new AlphaAnimation(0, 1);
			alphaIn.setDuration(500);
			viewCustomer.startAnimation(alphaIn);
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							AlphaAnimation alphaOut = new AlphaAnimation(1, 0);
							alphaOut.setDuration(500);
							viewCustomer.startAnimation(alphaOut);
							alphaOut.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									closeDialog();
								}
							});
						}
					});
				}
			}, 1500);

		} catch (Exception e) {
			// 忽略
		}

	}

	public static void makeToastForCustomer(Context mContext, int content) {
		if (viewCustomer != null) {
			viewCustomer = null;
		}
		if (tv_content != null) {
			tv_content = null;
		}
		if (rel_toast != null) {
			rel_toast = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		mDismissListener = null;
		try {
			viewCustomer = LayoutInflater.from(mContext).inflate(
					R.layout.toast_item_dialog, null);
			tv_content = (TextView) viewCustomer.findViewById(R.id.tv_content);
			rel_toast = (RelativeLayout) viewCustomer
					.findViewById(R.id.rel_toast);
			rel_toast.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {
					closeDialog();
				}
			});
			tv_content.setText(content);
			mDialog = new Dialog(mContext, R.style.TransparentDialog_Toast);
			mDialog.setContentView(viewCustomer);
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setCancelable(false);
			mDialog.show();
			AlphaAnimation alphaIn = new AlphaAnimation(0, 1);
			alphaIn.setDuration(500);
			viewCustomer.startAnimation(alphaIn);
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							AlphaAnimation alphaOut = new AlphaAnimation(1, 0);
							alphaOut.setDuration(500);
							viewCustomer.startAnimation(alphaOut);
							alphaOut.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									closeDialog();
								}
							});
						}
					});
				}
			}, 1500);

		} catch (Exception e) {
			// 忽略
		}

	}

	public static void makeToastForCustomer(Context mContext, int content,
			onToastDismiss callback) {
		if (viewCustomer != null) {
			viewCustomer = null;
		}
		if (tv_content != null) {
			tv_content = null;
		}
		if (rel_toast != null) {
			rel_toast = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		mDismissListener = callback;
		try {
			viewCustomer = LayoutInflater.from(mContext).inflate(
					R.layout.toast_item_dialog, null);
			tv_content = (TextView) viewCustomer.findViewById(R.id.tv_content);
			rel_toast = (RelativeLayout) viewCustomer
					.findViewById(R.id.rel_toast);
			rel_toast.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {
					closeDialog();
				}
			});
			tv_content.setText(content);
			mDialog = new Dialog(mContext, R.style.TransparentDialog_Toast);
			mDialog.setContentView(viewCustomer);
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setCancelable(false);
			mDialog.show();
			AlphaAnimation alphaIn = new AlphaAnimation(0, 1);
			alphaIn.setDuration(500);
			viewCustomer.startAnimation(alphaIn);
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							AlphaAnimation alphaOut = new AlphaAnimation(1, 0);
							alphaOut.setDuration(500);
							viewCustomer.startAnimation(alphaOut);
							alphaOut.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									closeDialog();
								}
							});
						}
					});
				}
			}, 1500);

		} catch (Exception e) {
			// 忽略
		}

	}

	public static void closeDialog() {

		if (mDismissListener != null)
			mDismissListener.onToastDismiss();

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

	public interface onToastDismiss {
		public void onToastDismiss();
	}

	public static void makeToastForCustomer(Context mContext, String content,
			onToastDismiss callback) {
		if (viewCustomer != null) {
			viewCustomer = null;
		}
		if (tv_content != null) {
			tv_content = null;
		}
		if (rel_toast != null) {
			rel_toast = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		mDismissListener = callback;
		try {
			viewCustomer = LayoutInflater.from(mContext).inflate(
					R.layout.toast_item_dialog, null);
			tv_content = (TextView) viewCustomer.findViewById(R.id.tv_content);
			rel_toast = (RelativeLayout) viewCustomer
					.findViewById(R.id.rel_toast);
			rel_toast.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {
					closeDialog();
				}
			});
			tv_content.setText(content);
			mDialog = new Dialog(mContext, R.style.TransparentDialog_Toast);
			mDialog.setContentView(viewCustomer);
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setCancelable(false);
			mDialog.show();
			AlphaAnimation alphaIn = new AlphaAnimation(0, 1);
			alphaIn.setDuration(500);
			viewCustomer.startAnimation(alphaIn);
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							AlphaAnimation alphaOut = new AlphaAnimation(1, 0);
							alphaOut.setDuration(500);
							viewCustomer.startAnimation(alphaOut);
							alphaOut.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									closeDialog();
								}
							});
						}
					});
				}
			}, 1500);

		} catch (Exception e) {
			// 忽略
		}

	}

	public static void makeToastForCustomer(Context mContext, String content,
			final boolean canClose) {
		if (viewCustomer != null) {
			viewCustomer = null;
		}
		if (tv_content != null) {
			tv_content = null;
		}
		if (rel_toast != null) {
			rel_toast = null;
		}

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		try {
			viewCustomer = LayoutInflater.from(mContext).inflate(
					R.layout.toast_item_dialog, null);
			tv_content = (TextView) viewCustomer.findViewById(R.id.tv_content);
			rel_toast = (RelativeLayout) viewCustomer
					.findViewById(R.id.rel_toast);
			rel_toast.setOnClickListener(new OnSingleClickListener() {

				@Override
				public void onSingleClick(View v) {
					if (canClose) {
						closeDialog();
					}
				}
			});
			tv_content.setText(content);
			mDialog = new Dialog(mContext, R.style.TransparentDialog_Toast);
			mDialog.setContentView(viewCustomer);
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setCancelable(false);
			mDialog.show();
			AlphaAnimation alphaIn = new AlphaAnimation(0, 1);
			alphaIn.setDuration(500);
			viewCustomer.startAnimation(alphaIn);
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							AlphaAnimation alphaOut = new AlphaAnimation(1, 0);
							alphaOut.setDuration(500);
							viewCustomer.startAnimation(alphaOut);
							alphaOut.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									closeDialog();
								}
							});
						}
					});
				}
			}, 1500);

		} catch (Exception e) {
			// 忽略
		}

	}

	/**
	 * 获取屏幕分辨率
	 * 
	 * @param context
	 * @return
	 */
	public static int[] getScreenDispaly(Context context) {
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		int width = windowManager.getDefaultDisplay().getWidth();// 手机屏幕的宽度
		int height = windowManager.getDefaultDisplay().getHeight();// 手机屏幕的高度
		int result[] = { width, height };
		return result;
	}
}
